import { useEffect, useMemo, useState } from 'react';
import { ApiHttp } from '../network/ApiHttp';
export interface IUseArticleInfoOptions {
  article_id?: number | string;
}
export interface IArticleInfo {
  link?: string;
  title?: string;
  breif?: string;
  html_url?: string;
  draft_id?: string;
  html_link?: string;
}

export async function getArticleInfo(article_id: undefined, ac?: AbortController): Promise<undefined>;
export async function getArticleInfo(article_id: string | number, ac?: AbortController): Promise<IArticleInfo>;
export async function getArticleInfo(article_id: string | number | undefined, ac?: AbortController): Promise<IArticleInfo | undefined>;
export async function getArticleInfo(article_id: string | number | undefined, ac?: AbortController): Promise<IArticleInfo | undefined> {
  if (!article_id) return void 0;
  return ApiHttp.get("/blog/detail", { id: article_id }, { ...ac }).then(r => r.data as IArticleInfo)
}

export default function useArticleInfo(opts: IUseArticleInfoOptions) {
  const { article_id } = opts;
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<IArticleInfo | undefined>(void 0);
  const [error, setError] = useState<any>(void 0);
  useEffect(() => {
    if (!article_id) return;
    setLoading(true);
    const c = new AbortController();
    getArticleInfo(article_id, c)
      .then(r => setData(r))
      .catch(e => setError(e))
      .finally(() => setLoading(false));
    return () => c.abort();
  }, [article_id]);
  return useMemo(() => ({ info: data, error, loading }), [data, error, loading]);
}

